package com.jxdinfo.hussar.example.common.schedulingtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.MdClientMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.model.MdClient;
import com.jxdinfo.hussar.example.common.schedulingtask.model.ProWorkorder;
import com.jxdinfo.hussar.example.common.schedulingtask.service.MdClientService;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.MdClientVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author QiaoBin
 * @Date 2024/4/02 15:49
 * @Description  md_client客户表的定时任务
 */
@Component
@AllArgsConstructor
public class MdClientScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(MdClientScheduleTask.class);

    private MdClientService mdClientService;
    private MdClientMapper mdClientMapper;
    
//    @Scheduled(cron = "*/5 * * * * ?")
//    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
//    @Scheduled(cron = "0 0 8 * * ?") // 每天早上 8 点触发任务
//    0 15 9 * * *   每天上午9:15执行
    @Scheduled(cron = "0 0 1 * * ?")  //凌晨一点执行
    public void mdClientTask() {
        extracted();
    }

    private void extracted() {
        logger.info("\n用友-客户表-定时任务-开始执行");
        LocalDateTime nowTime = LocalDateTime.now();
        synchronized ("mdClientTask"){
            logger.info("用友-客户表-开始查询客户表中最大的同步时间");
            LocalDateTime scheduleDate = mdClientMapper.selectMaxScheduleDate();
            String scheduleDateString = "";
            if (scheduleDate != null) {
                scheduleDateString = scheduleDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            //查询创建时间大于定时任务时间，查询出来后把所有数据全部插进去
            logger.info("\n用友-客户表-开始查询CBO_Customer表中创建时间大于任务时间的数据,查询参数scheduleDateString={}", scheduleDateString);
            List<MdClientVO> moreClientList = mdClientMapper.selectMoreSchedule(scheduleDateString);
            logger.info("\n用友-客户表-结束查询CBO_Customer表中创建时间大于任务时间的数据,查询结果moreClientList={}，size={}", moreClientList,moreClientList.size());
            if (moreClientList.size() > 0) {
                ArrayList<MdClient> mdClientList = new ArrayList<>();
                for (int i = 0; i < moreClientList.size(); i++) {
                    logger.info("\n用友-客户表-当前循环次数i={}", i);
                    MdClientVO mdClientVO = moreClientList.get(i);
                    MdClient mdClient = new MdClient();
                    mdClient.setClientId(mdClientVO.getClientId());
                    mdClient.setClientCode(mdClientVO.getClientCode());     // 客户编码
                    mdClient.setClientName(mdClientVO.getClientName());     // 客户名称
                    mdClient.setEnableFlag(mdClientVO.getEnableFlag());     // 是否启用
                    mdClient.setScheduleTime(nowTime);
                    mdClient.setCreateBy(mdClientVO.getCreateBy());
                    mdClient.setCreateTime(mdClientVO.getCreateTime());
                    mdClient.setUpdateBy(mdClientVO.getUpdateBy());
                    mdClient.setUpdateTime(mdClientVO.getUpdateTime());
                    mdClient.setErpClientId(mdClientVO.getClientId());
                    logger.info("\n用友-客户表-开始向list中存入数据，数据mdClient={},i={}", mdClient,i);
                    mdClientList.add(mdClient);
                }
                logger.info("\n用友-客户表-开始向mdClient表中插入数据，数据mdClientList={}", mdClientList);
                boolean b = mdClientService.saveBatch(mdClientList, 100);
                logger.info("\n用友-客户表-结束向mdClient表中插入数据，插入结果b={}", b);
            }
            if (scheduleDate == null) {
                logger.info("\n用友-客户表-查询不到任务时间，说明一次也没有同步，之间原封不动的插入就行,也就不需要后续更新");
                return;
            }
            if (scheduleDate != null) {
                logger.info("\n用友-客户表-开始查询CBO_Customer表中更新时间大于任务时间，查询参数scheduleDateString={}", scheduleDateString);
                List<MdClientVO> moreUpdateClientList = mdClientMapper.selectUpdateMoreSchedule(scheduleDateString);
                logger.info("\n用友-客户表-结束查询CBO_Customer表中更新时间大于任务时间,查询结果moreUpdateClientList={},数量size={}", moreUpdateClientList, moreUpdateClientList.size());

                if (moreUpdateClientList == null || moreUpdateClientList.size() == 0) {
                    logger.info("\n用友-客户表-没有查询到更新时间大于任务时间的CBO_Customer表中数据");
                    return;
                }
                // 转成map集合
                logger.info("\n用友-客户表-开始把用友表中更新时间大于任务时间的数据转换成主键、对象的map集合");
                Map<Long, MdClientVO> mdClientUpdateMap = moreUpdateClientList.stream().collect(Collectors.toMap(MdClientVO::getClientId, t -> t));
                logger.info("\n用友-客户表-开始获取用友表中更新时间大于任务时间的数据的主键");
                List<Long> clientIdList = moreUpdateClientList.stream().map(MdClientVO::getClientId).collect(Collectors.toList());
                logger.info("\n用友-客户表-CBO_Customer表更新时间大于任务时间的主键集合masterIdList={},size={}", clientIdList, clientIdList.size());

                logger.info("\n用友-客户表-开始查询md_client中master_id=CBO_Customer表中主键的数据,参数masterIdList={}", clientIdList);
                QueryWrapper<MdClient> mdClientQueryWrapper = new QueryWrapper<>();
                mdClientQueryWrapper.in("erp_client_id",clientIdList);
                mdClientQueryWrapper.eq("deleted_flag",0);
                List<MdClient> mdClientUpdateList = mdClientMapper.selectList(mdClientQueryWrapper);
                logger.info("\n用友-客户表-结束查询md_client中erp_client_id=erp表中主键的数据,结果mdClientUpdateList={},size={}", mdClientUpdateList, mdClientUpdateList.size());
                if (mdClientUpdateList.size() > 0) {
                    ArrayList<MdClient> updateMdClientList = new ArrayList<>();
                    for (int i = 0; i < mdClientUpdateList.size(); i++) {
                        logger.info("\n用友-客户表-当前更新时间大于任务时间，md_client表更新，次数i={}", i);
                        MdClient mdClient = mdClientUpdateList.get(i);
                        Long currentMasterId = mdClient.getErpClientId();
                        mdClient.setClientCode(mdClientUpdateMap.get(currentMasterId).getClientCode());              // 客户编码
                        mdClient.setClientName(mdClientUpdateMap.get(currentMasterId).getClientName());              // 客户名称
                        mdClient.setEnableFlag(mdClientUpdateMap.get(currentMasterId).getEnableFlag());              // 生效状态

                        mdClient.setScheduleTime(nowTime);
                        mdClient.setCreateBy(mdClientUpdateMap.get(currentMasterId).getCreateBy());
                        mdClient.setCreateTime(mdClientUpdateMap.get(currentMasterId).getCreateTime());
                        mdClient.setUpdateBy(mdClientUpdateMap.get(currentMasterId).getUpdateBy());
                        mdClient.setUpdateTime(mdClientUpdateMap.get(currentMasterId).getUpdateTime());
                        logger.info("\n用友-客户表-向updateMdClientList存储待要更新的客户表信息,mdClient={}", mdClient);
                        updateMdClientList.add(mdClient);
                    }
                    logger.info("\n用友-客户表-开始更新md_client数据,列表updateMdClientList={}", updateMdClientList);
                    boolean u = mdClientService.updateBatchById(updateMdClientList);
                    logger.info("\n用友-客户表-结束更md_client数据,更新结果u={}", u);
                }
            }
        }
        logger.info("\n用友-客户表-定时任务-结束执行");
    }
}
